import groovy.json.JsonOutput

properties([
        parameters([
                gitParameter(branch: '',
                        branchFilter: 'origin/(.*)',
                        defaultValue: 'master',
                        description: '',
                        name: 'branch',
                        type: 'PT_BRANCH_TAG',
                        useRepository: '.*Bucky.git'),
                choice(name: 'projectName', choices: ['xxl-admin', 'xxl-core'], description: 'project list'),
                choice(name: 'action', choices: ['deploy', 'start', 'stop', 'restart', 'rollback', 'install'], description: 'command action'),
                choice(name: 'runEnv', choices: ['test', 'prod'], description: 'The target environment'),


        ])
])

class Project {
    String projectName
    String gitUrl
    String basePath
    String targetPath
    String jarName
    String serverPort
    String adminPort
    String jvmParam
    String springParam

    Project(String projectName, String gitUrl, String basePath, String targetPath, String jarName, String serverPort, String adminPort, String jvmParam, String springParam) {
        this.projectName = projectName
        this.gitUrl = gitUrl
        this.basePath = basePath
        this.targetPath = targetPath
        this.jarName = jarName
        this.serverPort = serverPort
        this.adminPort = adminPort
        this.jvmParam = jvmParam
        this.springParam = springParam
    }

    Project(String projectName, String gitUrl) {
        this.projectName = projectName
        this.gitUrl = gitUrl
    }

    def commandPath() {
        basePath + "/" + projectName
    }

    def sourceJar() {
        targetPath + "/" + jarName
    }
}

baseGitUrl = 'git@gitee.com:btc8/Bucky.git'
branch = params.branch.startsWith('!No') ? 'master' : params.branch
projectName = params.projectName
action = params.action
runEnv = params.runEnv
basePath = '/home/admin'
baseJvmParam = runEnv == 'prod' ? '-Xmx512m -Xms512m' : '-Xmx128m -Xms128m'
baseSpringParam = ''

baseMap = [
        'xxl-admin': new Project('xxl-admin', baseGitUrl, basePath, './xxl-job-admin/target', 'xxl-job-admin-2.0.2-SNAPSHOT.jar', '8213', '8214', baseJvmParam, baseSpringParam),
        'xxl-core' : new Project('xxl-core', baseGitUrl),
]

node {

    stage('mvn build') {
        git branch: branch, credentialsId: 'ff834936-452d-4db7-8569-789bc70766a3', url: baseGitUrl
        //mvn构建
        if (action == "deploy" && projectName == "xxl-admin") {
            //定义mvn环境
            withEnv(["PATH+MAVEN=${tool 'M3'}/bin"]) {
                sh "mvn clean package -Dmaven.test.skip=true"
            }
        } else if (action == "install" && projectName == "xxl-core") {
            withEnv(["PATH+MAVEN=${tool 'M3'}/bin"]) {
                sh "mvn clean install -Dmaven.test.skip=true"
            }
        }
        //构建完成后,targetPath下jar会一直存在，即便是下一步切到另一个仓库，还会存在
        //看这个过程，可能是git拉代码时会临时改变workspace下的remote.origin.url，所以不冲突的文件是可以并存的，名称冲突的文件当然就被覆盖了
    }

    stage('deploy') {
        git branch: 'master', credentialsId: 'ff834936-452d-4db7-8569-789bc70766a3', url: 'git@gitee.com:btc8/test_script.git'
        if (projectName == "xxl-admin") {
            deployProject(projectName)
        }
    }

}

private void deployProject(String projectName) {
    println('do deploy project ' + projectName)
    Project pj = baseMap.get(projectName)
    def ansible_extras = [
            hosts            : runEnv == 'prod' ? 'prod-xxl-admin-nodes' : 'test-xxl-admin-nodes',
            pj_name          : pj.projectName,
            base_path        : pj.commandPath(),
            action           : action,
            jar_name         : pj.jarName,
            server_port      : pj.serverPort,
            admin_port       : pj.adminPort,
            run_env          : runEnv,
            jvm_param        : pj.jvmParam,
            spring_param     : pj.springParam,
            source_jar       : "${WORKSPACE}" + pj.sourceJar().substring(1),
            ansible_sudo_pass: 'Xixihaha'
    ]
    def extra_json = JsonOutput.toJson(ansible_extras)
    ansiblePlaybook colorized: true, inventory: './ci/ansible/hosts', playbook: './ci/ansible/playbook.yaml', extras: '--extra-vars \'' + extra_json + '\''
}